
package com.shuma.upms.user.exception;

import com.shuma.upms.user.domain.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice // 全局异常处理切面
public class GlobalExceptionHandler {

    /**
     * 捕获自定义的业务异常
     * @param e BusinessException实例
     * @return 统一的错误响应
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.warn("业务逻辑异常: {}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 【新增】处理JSR-303参数校验异常
     * @param e MethodArgumentNotValidException实例
     * @return 统一的错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e) {
        // 从异常对象中拿到 ObjectError 对象，并获取我们在 DTO 中定义好的 message
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        String errorMessage = objectError.getDefaultMessage();
        log.warn("校验失败: {}", errorMessage);
        return Result.error(errorMessage);
    }

    /**
     * 捕获所有其他未处理的系统异常
     * @param e Exception实例
     * @return 统一的系统错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e) {
        log.error("发生了未捕获的异常: {}", e.getMessage(), e);
        return Result.error("系统内部错误，请联系管理员");
    }

    /**
     * 【新增】处理自定义的认证异常
     * @param e AuthException实例
     * @return 统一的认证失败响应
     */
    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Void> handleAuthException(AuthException e) {
        log.warn("Authentication Failed: {}", e.getMessage());
        return Result.error(e.getMessage());
    }
}
